package server;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ContactManager {
    private static final String CONTACTS_FILE = "src/main/resources/contacts.txt";

    public synchronized List<String> getContacts() throws IOException {
        return readFile();
    }

    public synchronized void addContact(String name, String phone) throws IOException {
        List<String> contacts = readFile();
        contacts.add(name + ":" + phone);
        writeFile(contacts);
    }

    public synchronized void deleteContact(String name) throws IOException {
        List<String> contacts = readFile();
        contacts.removeIf(contact -> contact.startsWith(name + ":"));
        writeFile(contacts);
    }

    public synchronized void updateContact(String name, String newPhone) throws IOException {
        List<String> contacts = readFile();
        for (int i = 0; i < contacts.size(); i++) {
            if (contacts.get(i).startsWith(name + ":")) {
                contacts.set(i, name + ":" + newPhone);
            }
        }
        writeFile(contacts);
    }

    private List<String> readFile() throws IOException {
        List<String> contacts = new ArrayList<>();
        File file = new File(CONTACTS_FILE);
        if (!file.exists()) {
            return contacts; // 如果文件不存在，返回空列表
        }

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contacts.add(line);
            }
        }
        return contacts;
    }

    private void writeFile(List<String> contacts) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(CONTACTS_FILE))) {
            for (String contact : contacts) {
                writer.write(contact);
                writer.newLine();
            }
        }
    }
}
